package com.string.actortv.util;

import android.util.Log;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.string.actortv.dto.MovieInfo;
import com.string.actortv.dto.MovieList;
import com.string.actortv.dto.MovieTypeList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.string.actortv.util.CacheHelper.CACHE;

public class JxtcdUtil {

    private static final String BASE_URL = "https://www.jxtcd.com";
    private static final String BASE_PAGE_URL = "https://www.jxtcd.com/index.php";

    private static String getBaseTypeUrl(String action) {
        return "https://www.jxtcd.com/index.php?s=home-vod-type-id-" + action + "-picm-1-p-1";
    }

    public interface MovieTypeCallBack {
        void execute(List<MovieTypeList> movieTypeList);
    }

    /**
     * /html/body/div[2]/div[1]/div[2]/dl[1]/dd
     *
     * @param action
     * @param callBack
     */
    public static void getMovieTypeAsync(String action, MovieTypeCallBack callBack) {
        MyHttpUtil.getAsync(getBaseTypeUrl(action), html -> {
            Document document = Jsoup.parse(html);
            List<MovieTypeList> movieTypeLists = new ArrayList<>();
            Elements liElements = document.getElementById("mcid")
                    .getElementsByTag("li");
            for (Element li : liElements) {
                if (!li.getElementsByTag("a").get(0).text().equals("类型")) {
                    MovieTypeList movieTypeList = new MovieTypeList(li.getElementsByTag("a").get(0).text(), li.getElementsByTag("a").get(0).attr("data"));
                    movieTypeLists.add(movieTypeList);
                }
            }
            callBack.execute(movieTypeLists);
        }, null);
    }

    public interface MovieUrlCallBack {
        void execute(String playUrl);
    }

    public static void getMovieUrlAsync(String pageUrl, MovieUrlCallBack callBack) {
        MyHttpUtil.getAsync(pageUrl, html -> {
            Document document = Jsoup.parse(html);
            Element cmsPlay = document.getElementById("cms_play");
            String scriptStr = cmsPlay.getElementsByTag("script").get(0).html();
            String jsonStr = scriptStr.substring(scriptStr.indexOf("=") + 2)
                    .replace("\\", "").replace(";", "");
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            String playUrl = jsonObject.getString("url");
            callBack.execute(playUrl);
        }, null);
    }

    public interface MovieListCallBack {
        void execute(List<MovieList> movieList);
    }

    public static void getMovieListAsync(int pageNo, String searchStr,
                                         String type, String action,
                                         MovieListCallBack movieListCallBack) {
        String pageUrl;
        if (StrUtil.isEmpty(searchStr)) {
            if (StrUtil.isEmpty(type)) {
                pageUrl = BASE_PAGE_URL + "?s=home-vod-type-id-" + action + "-mcid-0-picm-1-p-" + pageNo;
            } else {
                pageUrl = BASE_PAGE_URL + "?s=home-vod-type-id-" + action + "-" + type + "-picm-1-p-" + pageNo;
            }
            if (CACHE.containsKey(pageUrl)
                    && CACHE.get(pageUrl) != null) {
                getList(pageUrl, searchStr, CACHE.get(pageUrl).toString(), movieListCallBack);
            } else {
                MyHttpUtil.getAsync(pageUrl, result -> getList(pageUrl, searchStr, result, movieListCallBack), null);
            }
        } else {
            pageUrl = BASE_PAGE_URL + "?s=home-search-index-wd-" + URLEncoder.encode(searchStr) + "-sid-1-p-" + pageNo;
            if (CACHE.containsKey(pageUrl)
                    && CACHE.get(pageUrl) != null) {
                getList(pageUrl, searchStr, CACHE.get(pageUrl).toString(), movieListCallBack);
            } else {
                Map<String, String> headerMap = new HashMap<>();
                headerMap.put("x-requested-with", "XMLHttpRequest");
                MyHttpUtil.getAsync(pageUrl, result -> getList(pageUrl, searchStr, result, movieListCallBack), headerMap);
            }
        }
    }

    private static void getList(String pageUrl, String searchStr,
                                String html, MovieListCallBack movieListCallBack) {
        if ("".equals(html)) {
            Log.d("JxtcdGetList", html);
            movieListCallBack.execute(null);
            return;
        }
        CACHE.put(pageUrl, html);
        if (StrUtil.isNotEmpty(searchStr)) {
            html = html.replace("\\", "");
            html = html.substring(1, html.length() - 1);
        }
        Document document = Jsoup.parse(html);
        List<MovieList> movieList = new ArrayList<>();
        //获取当前电影列表
        Elements movieElements;
        if (StrUtil.isNotEmpty(searchStr)) {
            Element content = document
                    .getElementById("content");
            movieElements = content
                    .getElementsByTag("ul").get(0)
                    .getElementsByTag("li");
        } else {
            Element content = document
                    .getElementById("content");
            movieElements = content
                    .getElementsByTag("li");
        }
        if (movieElements != null) {
            for (Element movieElement : movieElements) {
                Elements elements;
                if (StrUtil.isNotEmpty(searchStr)) {
                    elements = movieElement.getElementsByTag("div");
                } else {
                    elements = movieElement.getElementsByTag("a");
                }
                if (!elements.isEmpty()) {
                    String name;
                    String img;
                    String url;
                    if (StrUtil.isNotEmpty(searchStr)) {
                        name = elements.get(1).getElementsByTag("a").get(0).text();
                        img = elements.get(0).getElementsByTag("a").get(0).getElementsByTag("img").get(0).attr("data-original");
                        url = BASE_URL + elements.get(1).getElementsByTag("a").get(0).attr("href");
                    } else {
                        name = elements.get(0).attr("title");
                        img = elements.get(0).getElementsByTag("img").get(0).attr("data-original");
                        url = BASE_URL + elements.get(0).attr("href");
                    }
                    if (img.startsWith("//")) {
                        img = "https:" + img;
                    } else if (img.startsWith("/")) {
                        img = BASE_URL + img;
                    }
                    movieList.add(new MovieList(name, url, img));
                }
            }
        }
        movieListCallBack.execute(movieList);
    }

    public interface MovieInfoCallBack {
        void execute(MovieInfo movieInfo);
    }

    public static void getMovieInfoAsync(String href, String name, MovieInfoCallBack movieInfoCallBack) {
        //获取电影集数列表
        if (CACHE.containsKey(href)
                && CACHE.get(href) != null) {

            getInfo(name, CACHE.get(href).toString(), movieInfoCallBack);
        } else {
            MyHttpUtil.getAsync(href, movieHtml -> {
                if ("".equals(movieHtml)) {
                    movieInfoCallBack.execute(null);
                    return;
                }
                CACHE.put(href, movieHtml);

                getInfo(name, movieHtml, movieInfoCallBack);
            }, null);
        }
    }

    private static void getInfo(String name, String movieHtml, MovieInfoCallBack movieInfoCallBack) {
        Document document = Jsoup.parse(movieHtml);
        //视频图片
        Elements imgElements = document.getElementsByClass("video-pic");
        String img = imgElements.get(0).getElementsByTag("img").get(0).attr("data-original");
        //视频介绍
        Elements descElements = document.getElementsByClass("txt-hid");
        String desc = "";
        if (!descElements.isEmpty()) {
            desc = descElements.get(0).text();
        }
        Elements listElements = document
                .getElementById("con_playlist_1")
                .getElementsByTag("li");
        List<MovieInfo.SeasonList> seasonList = new ArrayList<>();
        if (listElements != null && !listElements.isEmpty()) {
            for (Element seasonElement : listElements) {
                String seasonName = seasonElement.text();
                String url = BASE_URL + seasonElement.getElementsByTag("a").get(0).attr("href");

                seasonList.add(new MovieInfo.SeasonList(seasonName, url));
            }
        }
        movieInfoCallBack.execute(new MovieInfo(name, img, desc, seasonList));
    }

}
